#!/bin/bash

localContainerName=$1
remoteImageName=$2
servicePort=$3
serviceName="nginx"

echo "容器名:$localContainerName 镜像:$remoteImageName 服务:$serviceName 端口:$servicePort"
if [[ -n $(docker ps -q -a -f "name=$localContainerName") ]]
  then
    echo "存在容器:$localContainerName"
    # 停止容器
    docker stop "$localContainerName"
    echo "停止容器:$localContainerName"
    # 删除容器
    docker rm "$localContainerName"
    echo "删除容器:$localContainerName"
fi

# 删除镜像
if [ $(docker image ls "$remoteImageName" | wc -l) -eq 2 ]
  then docker rmi "$remoteImageName"
  echo "删除镜像:$remoteImageName"
fi

docker pull "$remoteImageName"
docker run -itd --privileged=true --name "$localContainerName" -p "$servicePort:11000" "$remoteImageName" /sbin/init
docker exec "$localContainerName" systemctl enable "$serviceName"
docker exec "$localContainerName" systemctl start "$serviceName"
